
package parser;

import org.pdfbox.cos.COSDocument;
import org.pdfbox.pdfparser.PDFParser;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.pdmodel.PDDocumentInformation;
import org.pdfbox.util.PDFTextStripper;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;
 
public class PDFTextParser {
 
PDFParser parser;
String parsedText;
PDFTextStripper pdfStripper;
PDDocument pdDoc;
COSDocument cosDoc;
PDDocumentInformation pdDocInfo;
 
// PDFTextParser Constructor
public PDFTextParser() {}

// Extract text from PDF Document
String pdftoText(String fileName) {
 
System.out.println("Parsiando el texto del PDF " + fileName + "....");
File f = new File(fileName);
 
if (!f.isFile()) {
System.out.println("El archivo " + fileName + " no existe.");
return null;
}
 
try {
parser = new PDFParser(new FileInputStream(f));
} catch (Exception e) {
System.out.println("Imposible abrir el parser del PDF.");
return null;
}
 
try {
parser.parse();
cosDoc = parser.getDocument();
pdfStripper = new PDFTextStripper();
pdDoc = new PDDocument(cosDoc);
parsedText = pdfStripper.getText(pdDoc);
} catch (Exception e) {
System.out.println("Una excepcion ocurrio mientras se parseaba el PDF.");
e.printStackTrace();
try {
if (cosDoc != null) cosDoc.close();
if (pdDoc != null) pdDoc.close();
} catch (Exception e1) {
e.printStackTrace();
}
return null;
}
System.out.println("Listo!");
return parsedText;
}
 
// Write the parsed text from PDF to a file
void writeTexttoFile(String pdfText, String fileName) {
 
System.out.println("\nEscribiendo el contenido del PDF en el TXT " + fileName + "....");
try {
PrintWriter pw = new PrintWriter(fileName);
pw.print(pdfText);
pw.close();
} catch (Exception e) {
System.out.println("Una excepcion ocurrio mientras se copiaba el contedido del PDF al TXT.");
e.printStackTrace();
}
System.out.println("Listo!");
}
}
